<template>
  <v-layout>
    <Header />
    <v-main>
      <v-container fluid>
        <!-- 面包屑导航 -->
        <v-row class="mb-4">
          <v-col cols="12">
            <v-breadcrumbs
              :items="breadcrumbs"
              divider=">"
              class="pa-0"
            >
              <template v-slot:item="{ item }">
                <v-breadcrumbs-item
                  :to="item.to"
                  :disabled="item.disabled"
                  class="text-body-2"
                >
                  {{ item.title }}
                </v-breadcrumbs-item>
              </template>
            </v-breadcrumbs>
          </v-col>
        </v-row>

        <!-- 加载状态 -->
        <div v-if="loading" class="d-flex justify-center align-center py-12">
          <v-progress-circular
            indeterminate
            color="primary"
            size="64"
          ></v-progress-circular>
        </div>

        <!-- 错误提示 -->
        <v-alert
          v-if="error"
          type="error"
          variant="tonal"
          class="mb-6"
        >
          {{ error }}
        </v-alert>

        <!-- 商品详情内容 -->
        <div v-if="!loading && product" class="product-detail">
          <v-row>
            <!-- 商品图片 -->
            <v-col cols="12" md="6">
              <v-card flat class="product-image-card">
                <v-img
                  :src="product.image || defaultImage"
                  :alt="product.name"
                  height="400"
                  cover
                  class="rounded-lg"
                >
                  <template v-slot:placeholder>
                    <div class="d-flex align-center justify-center fill-height">
                      <v-progress-circular
                        color="grey-lighten-4"
                        indeterminate
                      ></v-progress-circular>
                    </div>
                  </template>
                </v-img>
              </v-card>
            </v-col>

            <!-- 商品信息 -->
            <v-col cols="12" md="6">
              <div class="product-info">
                <!-- 商品标题 -->
                <h1 class="text-h4 font-weight-bold text-primary mb-4">
                  {{ product.name }}
                </h1>

                <!-- 商品价格 -->
                <div class="price-section mb-6">
                  <div class="d-flex align-center mb-2">
                    <span class="text-h4 font-weight-bold text-error mr-3">
                      ¥{{ product.actual_price.toFixed(2) }}
                    </span>
                    <span 
                      v-if="product.retail_price > product.actual_price"
                      class="text-body-1 text-decoration-line-through text-grey"
                    >
                      ¥{{ product.retail_price.toFixed(2) }}
                    </span>
                  </div>
                  <v-chip
                    v-if="product.retail_price > product.actual_price"
                    color="success"
                    size="small"
                    variant="tonal"
                  >
                    节省 ¥{{ (product.retail_price - product.actual_price).toFixed(2) }}
                  </v-chip>
                </div>

                <!-- 商品状态信息 -->
                <v-row class="mb-6">
                  <v-col cols="6">
                    <div class="info-item">
                      <span class="text-body-2 text-grey">库存：</span>
                      <span class="font-weight-medium" :class="stockColor">
                        {{ stockText }}
                      </span>
                    </div>
                  </v-col>
                  <v-col cols="6">
                    <div class="info-item">
                      <span class="text-body-2 text-grey">销量：</span>
                      <span class="font-weight-medium">{{ product.sales_volume }}</span>
                    </div>
                  </v-col>
                  <v-col cols="6">
                    <div class="info-item">
                      <span class="text-body-2 text-grey">发货方式：</span>
                      <v-chip
                        :color="product.type === 1 ? 'success' : 'warning'"
                        size="small"
                        variant="tonal"
                      >
                        {{ product.type === 1 ? '自动发货' : '人工处理' }}
                      </v-chip>
                    </div>
                  </v-col>
                  <v-col cols="6" v-if="product.buy_limit_num > 0">
                    <div class="info-item">
                      <span class="text-body-2 text-grey">限购：</span>
                      <span class="font-weight-medium text-warning">
                        最多{{ product.buy_limit_num }}件
                      </span>
                    </div>
                  </v-col>
                </v-row>

                <!-- 购买数量选择 -->
                <div class="quantity-section mb-6">
                  <v-row align="center">
                    <v-col cols="auto">
                      <span class="text-body-1 font-weight-medium">购买数量：</span>
                    </v-col>
                    <v-col cols="auto">
                      <v-btn-toggle
                        v-model="quantity"
                        mandatory
                        variant="outlined"
                        divided
                      >
                        <v-btn
                          @click="decreaseQuantity"
                          :disabled="quantity <= 1"
                          icon="mdi-minus"
                          size="small"
                        ></v-btn>
                        <v-text-field
                          v-model.number="quantity"
                          type="number"
                          :min="1"
                          :max="maxQuantity"
                          hide-details
                          variant="outlined"
                          density="compact"
                          style="width: 80px"
                          class="text-center"
                        ></v-text-field>
                        <v-btn
                          @click="increaseQuantity"
                          :disabled="quantity >= maxQuantity"
                          icon="mdi-plus"
                          size="small"
                        ></v-btn>
                      </v-btn-toggle>
                    </v-col>
                  </v-row>
                </div>

                <!-- 购买提示 -->
                <v-alert
                  v-if="product.buy_prompt"
                  type="info"
                  variant="tonal"
                  class="mb-6"
                >
                  {{ product.buy_prompt }}
                </v-alert>

                <!-- 购买按钮 -->
                <div class="action-buttons">
                  <v-btn
                    color="primary"
                    size="large"
                    block
                    :disabled="!canPurchase"
                    @click="handlePurchase"
                    class="mb-3"
                  >
                    <v-icon left>mdi-cart-plus</v-icon>
                    立即购买 (¥{{ totalPrice.toFixed(2) }})
                  </v-btn>
                  <v-btn
                    variant="outlined"
                    size="large"
                    block
                    @click="goBack"
                  >
                    <v-icon left>mdi-arrow-left</v-icon>
                    返回商品列表
                  </v-btn>
                </div>
              </div>
            </v-col>
          </v-row>

          <!-- 商品详细描述 -->
          <v-row class="mt-8">
            <v-col cols="12">
              <v-card flat>
                <v-card-title class="text-h5 font-weight-bold text-primary">
                  商品详情
                </v-card-title>
                <v-divider class="mb-4"></v-divider>
                <v-card-text>
                  <div class="product-description">
                    <p v-if="product.gd_description" class="text-body-1 mb-4">
                      {{ product.gd_description }}
                    </p>
                    <div v-if="product.description" v-html="product.description"></div>
                    <p v-if="!product.gd_description && !product.description" class="text-grey text-center py-8">
                      暂无详细描述
                    </p>
                  </div>
                </v-card-text>
              </v-card>
            </v-col>
          </v-row>
        </div>

        <!-- 商品不存在 -->
        <div v-if="!loading && !product && !error" class="text-center py-12">
          <v-icon size="64" color="grey-lighten-1">mdi-package-variant-closed</v-icon>
          <p class="text-h6 mt-4 text-grey">商品不存在或已下架</p>
          <v-btn color="primary" @click="goBack" class="mt-4">
            返回首页
          </v-btn>
        </div>
      </v-container>
    </v-main>
  </v-layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Header from '~/components/Header.vue';
import defaultImage from '~/assets/images/card.png';

// 路由相关
const route = useRoute();
const router = useRouter();
const productId = route.params.id;

// 状态变量
const product = ref(null);
const loading = ref(true);
const error = ref('');
const quantity = ref(1);

/**
 * 面包屑导航数据
 */
const breadcrumbs = computed(() => [
  {
    title: '首页',
    to: '/',
    disabled: false
  },
  {
    title: product.value?.category_name || '商品分类',
    disabled: true
  },
  {
    title: product.value?.name || '商品详情',
    disabled: true
  }
]);

/**
 * 计算库存状态文本
 */
const stockText = computed(() => {
  if (!product.value) return '';
  if (product.value.in_stock <= 0) return '缺货';
  if (product.value.in_stock < 10) return `仅剩${product.value.in_stock}件`;
  return '现货充足';
});

/**
 * 计算库存状态颜色
 */
const stockColor = computed(() => {
  if (!product.value) return '';
  if (product.value.in_stock <= 0) return 'text-error';
  if (product.value.in_stock < 10) return 'text-warning';
  return 'text-success';
});

/**
 * 计算最大购买数量
 */
const maxQuantity = computed(() => {
  if (!product.value) return 1;
  let max = product.value.in_stock;
  if (product.value.buy_limit_num > 0) {
    max = Math.min(max, product.value.buy_limit_num);
  }
  return Math.max(1, max);
});

/**
 * 计算总价格
 */
const totalPrice = computed(() => {
  if (!product.value) return 0;
  return product.value.actual_price * quantity.value;
});

/**
 * 判断是否可以购买
 */
const canPurchase = computed(() => {
  return product.value && 
         product.value.in_stock > 0 && 
         product.value.is_open === 1 &&
         quantity.value > 0 &&
         quantity.value <= maxQuantity.value;
});

/**
 * 获取商品详情数据
 */
const fetchProductDetail = async () => {
  try {
    loading.value = true;
    error.value = '';
    
    const response = await $fetch(`/api/goods/${productId}`);
    
    if (response.success) {
      product.value = response.data;
      // 设置页面标题
      useHead({
        title: `${product.value.name} - 商品详情`
      });
    } else {
      error.value = response.message || '获取商品详情失败';
    }
  } catch (err) {
    console.error('获取商品详情错误:', err);
    error.value = '获取商品详情失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

/**
 * 增加购买数量
 */
const increaseQuantity = () => {
  if (quantity.value < maxQuantity.value) {
    quantity.value++;
  }
};

/**
 * 减少购买数量
 */
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

/**
 * 处理购买操作
 */
const handlePurchase = () => {
  if (!canPurchase.value) return;
  
  // TODO: 实现购买逻辑，跳转到订单页面或购买流程
  console.log('购买商品:', {
    productId: product.value.id,
    quantity: quantity.value,
    totalPrice: totalPrice.value
  });
  
  // 这里可以跳转到购买页面或打开购买对话框
  // router.push(`/order/create?productId=${product.value.id}&quantity=${quantity.value}`);
};

/**
 * 返回上一页或首页
 */
const goBack = () => {
  if (window.history.length > 1) {
    router.go(-1);
  } else {
    router.push('/');
  }
};

// 监听数量变化，确保在有效范围内
watch(quantity, (newVal) => {
  if (newVal < 1) {
    quantity.value = 1;
  } else if (newVal > maxQuantity.value) {
    quantity.value = maxQuantity.value;
  }
});

// 页面加载时获取数据
onMounted(() => {
  fetchProductDetail();
});

// 设置页面元信息
useHead({
  title: '商品详情',
  meta: [
    { name: 'description', content: '查看商品详细信息和购买' }
  ]
});
</script>

<style scoped>
.product-detail {
  max-width: 1200px;
  margin: 0 auto;
}

.product-image-card {
  position: sticky;
  top: 20px;
}

.product-info {
  padding: 0 16px;
}

.price-section {
  border-left: 4px solid rgb(var(--v-theme-primary));
  padding-left: 16px;
  background: rgba(var(--v-theme-primary), 0.05);
  border-radius: 0 8px 8px 0;
  padding: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.quantity-section {
  padding: 16px;
  border: 1px solid rgba(var(--v-theme-on-surface), 0.12);
  border-radius: 8px;
  background: rgba(var(--v-theme-surface), 0.5);
}

.action-buttons {
  position: sticky;
  bottom: 20px;
  background: rgba(var(--v-theme-surface), 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  border-radius: 12px;
  border: 1px solid rgba(var(--v-theme-on-surface), 0.12);
}

.product-description {
  line-height: 1.8;
}

.product-description :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 16px 0;
}

.product-description :deep(p) {
  margin-bottom: 16px;
}

.product-description :deep(h1),
.product-description :deep(h2),
.product-description :deep(h3),
.product-description :deep(h4),
.product-description :deep(h5),
.product-description :deep(h6) {
  margin: 24px 0 16px 0;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 960px) {
  .product-image-card {
    position: static;
  }
  
  .product-info {
    padding: 16px 0;
  }
  
  .action-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    border-radius: 0;
    border-left: none;
    border-right: none;
    border-bottom: none;
    z-index: 1000;
  }
  
  .product-detail {
    padding-bottom: 120px;
  }
}
</style>